
#include "string.h"
#include "type.h"
#include "jxos_config.h"
#include "jxos_event.h"

#if (JXOS_ENENT_ENABLE == 1)&&(EVENT_MAX != 0)

static uint8_t event_mark_list[((EVENT_MAX-1)/8) + 1];
static uint8_t event_count = 0;

void jxos_event_init(void)
{
	memset(event_mark_list, 0, ((EVENT_MAX-1)/8) + 1);
    event_count = 0;
}

JXOS_EVENT_HANDLE jxos_event_create(void)
{
    if(event_count < EVENT_MAX){
        event_count++;
        return event_count;
    }
    else{
        return 0;
    }
}

//jxos_event_delete

uint8_t jxos_event_set(JXOS_EVENT_HANDLE event_h)
{
	uint8_t* event;
    uint8_t mark;
    event_h -= 1;
    if(event_h < event_count){
		event = &event_mark_list[event_h/8];
		mark = 1<<(event_h%8);
		/***critical section***/
        (*event) |= mark;
		/**********************/
        return 1;
    }
    else{
        return 0;
    }
}

uint8_t jxos_event_wait(JXOS_EVENT_HANDLE event_h) //if wait event success, the event will reset automatically
{
	uint8_t* event;
    uint8_t mark;
    uint8_t mark_temp;
    event_h -= 1;
    if(event_h < event_count){
		event = &event_mark_list[event_h/8];
		mark = 1<<(event_h%8);
		mark_temp = ~mark;
        if(((*event)&mark) != 0){
            /***critical section***/
            (*event) &= mark_temp;
            /**********************/
            return 1;
        }
        else{
            return 0;
        }
    }
    else{
        return 0xff;
    }
}

uint8_t jxos_event_check_empty_all(void)
{
	uint8_t i;
	if(event_count == 0){
        return 1;
	}
	for(i = 0; i <= ((event_count-1)/8); i++){
        if(event_mark_list[i] != 0){
            return 0;
        }
	}
	return 1;
}

//uint32_t jxos_event_clear(uint8_t id)
//{
//    if(id < event_count){
//        /***critical section***/
//        event_mark &= ~(1<<id);
//        /**********************/
//    }
//}

#endif // JXOS_ENENT_ENABLE
